//
//  150. 逆波兰表达式求值.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/10.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution150 {
    func evalRPN(_ tokens: [String]) -> Int {
        var statck: [String] = []
        for item in tokens {
            if item == "+" {
                let second = statck.removeLast()
                let first = statck.removeLast()
                let result = Int(first)! + Int(second)!
                statck.append(String(result))
            } else if item == "-" {
                let second = statck.removeLast()
                let first = statck.removeLast()
                let result = Int(first)! - Int(second)!
                statck.append(String(result))
            } else if item == "*" {
                let second = statck.removeLast()
                let first = statck.removeLast()
                let result = Int(first)! * Int(second)!
                statck.append(String(result))
            } else if item == "/" {
                let second = statck.removeLast()
                let first = statck.removeLast()
                let result = Int(first)! / Int(second)!
                statck.append(String(result))
            } else {
                statck.append(item)
            }
        }
        let top = statck.last!
        return Int(top)!
    }
    
    
    static func test() {
        // 加入这是解析语法树得到的一个表达式
        let tokens = ["2","1","+","3","*"]
        let solution = Solution150()
        let result = solution.evalRPN(tokens)
        print(result)
    }
}
